package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.mapper.DishFlavorMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@Service
public class DishServiceImpl implements DishService {

    @Autowired(required = false)
    private DishMapper dishMapper;

    @Autowired(required = false)
    private DishFlavorMapper dishFlavorMapper;

    @Autowired(required = false)
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        dishDto.setStatus(1);
        dishMapper.save(dishDto);//保存菜品
        Long dishId = dishDto.getId();

        List<DishFlavor> dishFlavorList = dishDto.getFlavors().stream().map(dishFlavor -> {
            dishFlavor.setDishId(dishId);
            dishFlavor.setCreateTime(LocalDateTime.now());
            dishFlavor.setUpdateTime(LocalDateTime.now());
            dishFlavor.setUpdateUser(dishDto.getUpdateUser());
            dishFlavor.setCreateUser(dishDto.getCreateUser());
            return dishFlavor;
        }).collect(Collectors.toList());

        dishFlavorMapper.saveBatch(dishFlavorList);
        //5. 由于菜品的数据已经发生变化了，那么需要清空缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
    }

    @Override
    public Page<DishDto> page(Integer page, Integer pageSize, String name) {
        //1. 设置当前页与页面大小
        PageHelper.startPage(page,pageSize);
        //2. 查找页面的数据
        List<Dish> dishList = dishMapper.findByName(name);

        //3.构建pageInfo对象
        PageInfo<Dish> pageInfo = new PageInfo<>(dishList);

        //3. 由于页面需要存在CategoryName，所以把Dish转换为DishDto集合
        List<DishDto> dishDtoList = new ArrayList<>();
        if(pageInfo.getList()!=null){
            for (Dish dish : pageInfo.getList()) {
                DishDto dishDto = new DishDto();
                BeanUtils.copyProperties(dish,dishDto);
                Category category = categoryService.findById(dish.getCategoryId());
                if(category != null){
                    dishDto.setCategoryName(category.getName());
                }else {
                    dishDto.setCategoryName("暂无类别");
                }
                dishDtoList.add(dishDto);
            }
        }

        Page<DishDto> pageResult = new Page<>(dishDtoList,page,pageSize,pageInfo.getTotal());
        return pageResult;
    }

    @Override
    public DishDto getByIdWithFlavor(Long id) {
        Dish dish = dishMapper.findById(id);
        List<DishFlavor> flavorList = dishFlavorMapper.findByDishId(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        dishDto.setFlavors(flavorList);
        return dishDto;
    }

    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
        dishMapper.update(dishDto);

        dishFlavorMapper.deleteById(dishDto.getId());

        //3. 把口味数据保存更新时间与更新人
        List<DishFlavor> dishFlavorList = dishDto.getFlavors().stream().map(dishFlavor -> {
            dishFlavor.setDishId(dishDto.getId());
            dishFlavor.setCreateTime(dishDto.getCreateTime());
            dishFlavor.setCreateUser(dishDto.getCreateUser());
            dishFlavor.setUpdateUser(dishDto.getUpdateUser());
            dishFlavor.setUpdateTime(dishDto.getUpdateTime());
            return dishFlavor;
        }).collect(Collectors.toList());
        dishFlavorMapper.saveBatch(dishFlavorList);
        //5. 由于菜品的数据已经发生变化了，那么需要清空缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
    }

    @Override
    public List<DishDto> findByCategoryId(Long categoryId,Integer status) {

        List<DishDto> dishDtoList = null;
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String key="dish_"+categoryId+"_"+status;
        dishDtoList = (List<DishDto>) valueOperations.get(key);
        if(dishDtoList==null){
            List<Dish> dishList = dishMapper.findByCategoryId(categoryId);
            dishDtoList=dishList.stream().map(dish -> {
                DishDto dishDto = new DishDto();
                BeanUtils.copyProperties(dish,dishDto);
                List<DishFlavor> dishFlavors = dishFlavorMapper.findByDishId(dishDto.getId());
                dishDto.setFlavors(dishFlavors);
                Category category = categoryService.findById(dish.getCategoryId());
                dishDto.setCategoryName(category.getName());
                return dishDto;
            }).collect(Collectors.toList());
            valueOperations.set(key,dishDtoList,60*24, TimeUnit.MINUTES);
        }

        return dishDtoList;
    }

    @Override
    @Transactional
    public void deleteByIds(List<Long> ids) {
        dishMapper.deleteByIds(ids);
        dishFlavorMapper.deleteByDishIds(ids);
    }

    @Override
    @Transactional
    public void updateStatus(List<Long> ids, DishDto dishDto, Integer status) {

        Dish dish = new Dish();
        dish.setUpdateTime(dishDto.getUpdateTime());
        dish.setUpdateUser(dishDto.getUpdateUser());

        DishFlavor dishFlavor = new DishFlavor();
        dishFlavor.setUpdateTime(dishDto.getUpdateTime());
        dishFlavor.setUpdateUser(dishDto.getUpdateUser());
        /*if(status==0){
            //批量停售
            dishMapper.updateStopStatus(ids,dish);
        }else{
            dishMapper.updateStartStatus(ids,dish);
        }*/
        dishMapper.updateStatus(ids,dish,status);


        dishFlavorMapper.updateByDishIds(ids,dishFlavor);
    }


}

